package com.oa.gongwen.controller;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.oa.gongwen.util.Constants;
import com.oa.office.util.UtilHelp;
/**
 * @author Cody
 * @version V1.0 
 */
@Controller
public class FileUploadController {

    @RequestMapping(value="/{formName}")
     public String loginForm(@PathVariable String formName) {
        // 动态跳转页面
        return formName;
    }
    private String lpath= Constants.IMAGE_PATH;
    //上传文件会自动绑定到MultipartFile中
    @RequestMapping(value = "/uploades", method = RequestMethod.POST)
    public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file, ModelMap model) {
      System.out.println("开始");
      String path = request.getSession().getServletContext().getRealPath("uploades");
      String fileName = file.getOriginalFilename();
      // String fileName = new Date().getTime()+".jpg";
      System.out.println(path);
      File targetFile = new File(path, fileName);
      if (!targetFile.exists()) {
        targetFile.mkdirs();
      }
   
      // 保存
      try {
        file.transferTo(targetFile);
      } catch (Exception e) {
        e.printStackTrace();
      }
      model.addAttribute("fileUrl", request.getContextPath() + "/upload/" + fileName);
      return "result";
    }

     @RequestMapping(value = "/upLoadFile.do", method = RequestMethod.POST)  
     public void upLoadFile(HttpServletRequest request,HttpServletResponse response)  
             throws IllegalStateException, IOException {  
         // @RequestParam("file") MultipartFile file,  
         CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(  
                 request.getSession().getServletContext());  
         // 判断 request 是否有文件上传,即多部分请求  
         if (multipartResolver.isMultipart(request)) {  
             // 转换成多部分request  
             MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;  
             // 取得request中的所有文件名  
             Iterator<String> iter = multiRequest.getFileNames();  
             while (iter.hasNext()) {  
                 // 取得上传文件  
                 MultipartFile f = multiRequest.getFile(iter.next());  
                 if (f != null) {  
                	 SimpleDateFormat time=new SimpleDateFormat("yyyyMMdd-HHmmss");
                	 
                     // 取得当前上传文件的文件名称  
                     String myFileName = time.format(new Date())+f.getOriginalFilename();  
                     // 如果名称不为“”,说明该文件存在，否则说明该文件不存在  
                     if (myFileName.trim() != "") {  
                         // 定义上传路径  
                         String path = lpath + myFileName;
                         File localFile = new File(path);  
                         f.transferTo(localFile);  
                         response.getWriter().write(myFileName);
                     }  
                 }  
             }  
         }
     }  

     @RequestMapping(value="/download")
     public ResponseEntity<byte[]> download(HttpServletRequest request,
             String filename,
             Model model)throws Exception {
        //下载文件路径
        String path = request.getServletContext().getRealPath(lpath);
        File file = new File(path + File.separator + filename);
        HttpHeaders headers = new HttpHeaders();  
        //下载显示的文件名，解决中文名称乱码问题  
        String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName); 
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
                headers, HttpStatus.CREATED);  
     }
}